import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';

import '../../../core/controller/app_controller.dart';
import '../../../core/controller/im_controller.dart';
import '../../../routes/app_navigator.dart';
import '../chat_logic.dart';

class ChatSetupLogic extends GetxController {
  final chatLogic = Get.find<ChatLogic>(tag: GetTags.chat);
  final appLogic = Get.find<AppController>();
  final imLogic = Get.find<IMController>();
  late Rx<ConversationInfo> conversationInfo;
  late StreamSubscription ccSub;
  late StreamSubscription fcSub;
  final domainFaceURL = ''.obs;
  final isDomainReady = false.obs;

    // 添加自定义免打扰状态
  final customNotDisturb = false.obs;

  String get conversationID => conversationInfo.value.conversationID;

  bool get isPinned => conversationInfo.value.isPinned == true;
  
   // 修改isNotDisturb getter，使用自定义状态
  bool get isNotDisturb => customNotDisturb.value;


  @override
  void onClose() {
    ccSub.cancel();
    fcSub.cancel();
    super.onClose();
  }

  @override
  void onInit() {
    conversationInfo = Rx(Get.arguments['conversationInfo']);
    final sourceID = conversationInfo.value.conversationType == ConversationType.single
        ? conversationInfo.value.userID
        : conversationInfo.value.groupID;

    _refreshDomainProfile();

    OpenIM.iMManager.conversationManager
        .getOneConversation(sourceID: sourceID!, sessionType: conversationInfo.value.conversationType!)
        .then((value) {
      conversationInfo.value = value;
      _refreshDomainProfile();
    });

    ccSub = imLogic.conversationChangedSubject.listen((newList) {
      for (var newValue in newList) {
        if (newValue.conversationID == conversationID) {
          conversationInfo.update((val) {
            val?.burnDuration = newValue.burnDuration ?? 30;
            val?.isPrivateChat = newValue.isPrivateChat;
            val?.isPinned = newValue.isPinned;
            val?.recvMsgOpt = newValue.recvMsgOpt;
            val?.isMsgDestruct = newValue.isMsgDestruct;
            val?.msgDestructTime = newValue.msgDestructTime;
            val?.showName = newValue.showName;
          });
          break;
        }
      }
    });

    fcSub = imLogic.friendInfoChangedSubject.listen((value) {
      if (conversationInfo.value.userID == value.userID) {
        conversationInfo.update((val) {
          val?.showName = value.getShowName();
          // val?.faceURL = value.faceURL;
        });
      }
    });

    // 加载自定义免打扰状态
    customNotDisturb.value = DataSp.getCustomNotDisturb(conversationID);

    super.onInit();
  }

  void createGroup() => AppNavigator.startCreateGroup(defaultCheckedList: [
        UserInfo(
          userID: conversationInfo.value.userID,
          // faceURL: conversationInfo.value.faceURL,
          nickname: conversationInfo.value.showName,
        ),
        OpenIM.iMManager.userInfo,
      ]);

  void viewUserInfo() => AppNavigator.startUserProfilePane(
        userID: conversationInfo.value.userID!,
        nickname: conversationInfo.value.showName,
        faceURL: domainFaceURL.value,
      );

  Future<void> _refreshDomainProfile() async {
    if (conversationInfo.value.conversationType != ConversationType.single) return;
    final uid = conversationInfo.value.userID;
    if (uid == null || uid.isEmpty) return;
    try {
      final profile = await Apis.getUserProfileByOpenIMID(uid);
      if (profile != null) {
        domainFaceURL.value = profile.faceURL ?? domainFaceURL.value;
        isDomainReady.value = true;
        conversationInfo.update((val) {
          val?.faceURL = profile.faceURL ?? val?.faceURL;
          val?.showName = profile.nickname ?? val?.showName;
        });
      }
    } catch (_) {}
  }

  // 查找聊天记录
  void searchChatHistory() async {
    // 使用聊天历史搜索功能并处理返回结果
    final result = await AppNavigator.startChatHistorySearch(
      conversationID: conversationInfo.value.conversationID,
      conversationInfo: conversationInfo.value,
    );
    
    // 处理搜索返回的结果
    if (result != null && result is Map<String, dynamic>) {
      final action = result['action'];
      
      if (action == 'jumpToMessage') {
        final message = result['message'] as Message?;
        
        if (message != null) {
          // 返回到聊天页面并传递搜索消息
          Get.back(result: {
            'action': 'jumpToMessage',
            'message': message,
          });
        }
      }
    }
  }

  // 修改切换免打扰状态的方法
  void toggleNotDisturb() async {
    try {
      final newValue = !customNotDisturb.value;
      // 保存到本地存储而不是调用OpenIM的setConversation
      await DataSp.putCustomNotDisturb(conversationID, newValue);
      customNotDisturb.value = newValue;
      IMViews.showToast(newValue ? '已开启免打扰' : '已关闭免打扰');
    } catch (e) {
      IMViews.showToast('设置失败：$e');
    }
  }

  // 切换置顶状态
  void toggleTopConversation() async {
    try {
      final newValue = !isPinned;
      final req = ConversationReq(isPinned: newValue);
      await OpenIM.iMManager.conversationManager.setConversation(
        conversationID,
        req,
      );
      IMViews.showToast(newValue ? '已置顶' : '已取消置顶');
    } catch (e) {
      IMViews.showToast('设置失败：$e');
    }
  }

  // 提醒设置
  void openNotificationSettings() {
    // 跳转到通知设置页面
    AppNavigator.startGeneralSettings();
    IMViews.showToast('请在通用设置中配置提醒选项');
  }

  // 设置聊天背景
  void setChatBackground() {
    // 显示背景选择对话框
    Get.dialog(
      AlertDialog(
        title: Text('设置聊天背景'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(Icons.image),
              title: Text('从相册选择'),
              onTap: () {
                Get.back();
                _selectBackgroundFromGallery();
              },
            ),
            ListTile(
              leading: Icon(Icons.palette),
              title: Text('选择默认背景'),
              onTap: () {
                Get.back();
                _selectDefaultBackground();
              },
            ),
            ListTile(
              leading: Icon(Icons.restore),
              title: Text('恢复默认'),
              onTap: () {
                Get.back();
                _resetToDefaultBackground();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
        ],
      ),
    );
  }

  // 从相册选择背景
  void _selectBackgroundFromGallery() {
    IMViews.showToast('从相册选择背景功能开发中');
    // TODO: 实现从相册选择背景图片的功能
  }

  // 选择默认背景
  void _selectDefaultBackground() {
    IMViews.showToast('选择默认背景功能开发中');
    // TODO: 实现选择预设背景的功能
  }

  // 恢复默认背景
  void _resetToDefaultBackground() {
    IMViews.showToast('已恢复默认背景');
    // TODO: 实现恢复默认背景的功能
  }

  // 清空聊天记录
  void clearChatHistory() async {
    final confirm = await Get.dialog(CustomDialog(
      title: '清空聊天记录',
      content: '确定要清空与"${conversationInfo.value.showName}"的聊天记录吗？此操作不可恢复。',
      rightText: '清空',
      leftText: '取消',
    ));
    
    if (confirm == true) {
      try {
        await OpenIM.iMManager.conversationManager.clearConversationAndDeleteAllMsg(
          conversationID: conversationID,
        );
        // 清空聊天页面的消息列表
        chatLogic.clearAllMessage();
        IMViews.showToast('聊天记录已清空');
      } catch (e) {
        IMViews.showToast('清空失败：$e');
      }
    }
  }

  // 投诉用户
  void reportUser() async {
    final confirm = await Get.dialog(CustomDialog(
      title: '投诉用户',
      content: '确定要投诉用户"${conversationInfo.value.showName}"吗？',
      rightText: '投诉',
      leftText: '取消',
    ));
    
    if (confirm == true) {
      // 显示投诉原因选择对话框
      _showReportReasonDialog();
    }
  }

  // 显示投诉原因选择对话框
  void _showReportReasonDialog() {
    final reasons = [
      '发送垃圾信息',
      '发送不当内容',
      '骚扰他人',
      '诈骗行为',
      '其他原因',
    ];

    Get.dialog(
      AlertDialog(
        title: Text('选择投诉原因'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: reasons.map((reason) => ListTile(
            title: Text(reason),
            onTap: () {
              Get.back();
              _submitReport(reason);
            },
          )).toList(),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
        ],
      ),
    );
  }

  // 提交投诉
  void _submitReport(String reason) {
    // TODO: 实现实际的投诉提交逻辑
    IMViews.showToast('投诉已提交，感谢您的反馈');
    print('投诉用户: ${conversationInfo.value.userID}, 原因: $reason');
  }
}